import 'package:flutter/foundation.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_utils.dart';

/// Descriptions:
/// User: tangzhentao
/// Date: 2:05 下午 2021/12/5
///

class WebViewModel extends Viewmodel {
  String? title;
  final String url;

  InAppWebViewController? webViewController;

  /// webview设置
  final settings = InAppWebViewSettings(
    isInspectable: kDebugMode,
    mediaPlaybackRequiresUserGesture: false,
    allowsInlineMediaPlayback: true,
    iframeAllow: 'camera; microphone',
    iframeAllowFullscreen: true);

  /// 刷新
  PullToRefreshController? pullToRefreshController;

  bool _loading = true;
  bool get loading => _loading;
  set loading(bool value) {
    if (_loading != value) {
      _loading = value;
      notifyListeners();
    }
  }

  bool _canBack = false;
  bool get canBack => _canBack;

  WebViewModel(this.url, this.title) {
    pullToRefreshController = kIsWeb
        ? null
        : PullToRefreshController(
      settings: PullToRefreshSettings(
        color: XfgColor.theme,
      ),
      onRefresh: () async {
        if (defaultTargetPlatform == TargetPlatform.android) {
          webViewController?.reload();
        } else if (defaultTargetPlatform == TargetPlatform.iOS) {
          webViewController?.loadUrl(urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );
  }

  /// 设置控制器
  void setController(InAppWebViewController controller) {
    webViewController = controller;
    webViewController!.addJavaScriptHandler(handlerName: 'myHandlerName', callback: (data) {
      xfgPrint.call('js方法func, 参数: $data');
    });
  }

  Future changeRoute(InAppWebViewController controller) async {
    _canBack = await controller.canGoBack();
    notifyListeners();
  }

  @override
  void dispose() {
    webViewController?.dispose();
    webViewController = null;
    super.dispose();
  }
}